<template>
  <el-dialog v-dialogDrag v-if="popenevTVisible" title="请选择人员" :visible.sync="popenevTVisible" :before-close="handleCancel" width="770px" :close-on-click-modal="false">
    <div class="choice-person-box">
      <!-- 机构 -->
      <div class="org-list">
        <!-- 搜索框 -->
        <el-input class="search-input" placeholder="搜索" size="mini" v-model="searchoOrgkey">
          <i slot="suffix" class="el-input__icon el-icon-search" style="font-size:16px;cursor: pointer;margin-top: 2px;"></i>
        </el-input>
        <el-scrollbar ref="orgScroll" class="scorll-Y">
          <el-tree class="filter-tree" :data="treeData" :show-checkbox="multiple" :props="{ label: 'orgCommonname' }" node-key="unid" :default-expanded-keys="expandedKey" :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="false" :check-strictly="true" @check-change="onCheckOrg" @node-click="handleNodeClick" :filter-node-method="filterOrgNode" ref="orgTree">
            <span class="custom-tree-node" slot-scope="{ node,data }">
              <span>
                <i v-if="data.isCompany && data.unid" class='el-icon-office-building'></i>
                <i v-if="data.unid && !data.isCompany" class='el-icon-s-home'></i>
                {{ node.label }}</span>
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
      <!-- 人员列表 -->
      <div class="person-list" v-loading="loading">
        <!-- 搜索框 -->
        <div style="display: flex;align-items: center;">
          <el-checkbox style="margin-top:20px;margin-left:10px" v-model="checkAll" v-if="multiple" @change="handleCheckAllChange">全选</el-checkbox>
          <el-input class="search-input" placeholder="搜索" size="mini" v-model="searchoPersonKey" >
            <i slot="suffix" class="el-input__icon el-icon-search" style=";font-size:16px;cursor: pointer; margin-top: 2px;"></i>
          </el-input>
        </div>
        <el-scrollbar class="scorll-Y" ref="scrollMenuRef">
          <el-checkbox-group v-model="personUnidArr">
            <el-checkbox class="person-item" @change="onChangePerson" v-for="(pre_item, index) in personData" :label="pre_item.unid + '_' + pre_item.personCommonname" :key="index">{{ pre_item.personCommonname}}</el-checkbox>
          </el-checkbox-group>
        </el-scrollbar>
      </div>
      <!-- 人员列表 -->
      <div class="person-list">
        <div class="search-input" style="line-height:32px;font-weight: 700">
          已选人员({{checkPerosnList.length}})
          <el-button type="text" @click="handelEmpty">清空</el-button>
        </div>
        <el-scrollbar class="scorll-Y">
          <div class="person-item" v-for="(pre_item, index) in checkPerosnList" :label="pre_item.unid" :key="index">
            {{ pre_item.personCommonname }}
            <i class="btn-person-cacle el-icon-circle-close" @click="handleDelPerson(pre_item)" />
          </div>
        </el-scrollbar>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleOk">确定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import
{
  getCompanyTree, treeselect
} from "../../api/module/systemOrg/systemOrg.js";
import
{
  debounce
} from "../../utils/index.js";
import { getPersonList, getPersonListAll } from "../../api/system/person/api.js";
import PinYinMatch from "pinyin-match";
import { mapGetters } from 'vuex'
export default {
  data()
  {
    return {
      popenevTVisible: true,
      multiple: false,
      leftChecked: [],//记录左侧勾选人员unid数组
      treeData: [], //机构列表
      personData: [], //人员列表
      //promise 状态
      expandedKey: [],
      promiseStatus: null,
      searchoOrgkey: "", //机构搜索
      searchoPersonKey: "",//人员搜索
      searchkey: "",
      parame: {
        pageNo: 1,
        pageSize: 100,
        delFlag: 0,
        state: 0,
        orgUnid: null,
      },
      //是否全选
      checkAll: false,
      replaceFields: {
        title: "personCommonname", key: "unid"
      },
      //是否显示所有单位人员
      allCompany: false,
      //全部人员
      allPersonList: [],
      //已选人员unid
      personUnidArr: [],
      //已选人员数据 unid作为key
      allPersonObj: {},
      //总数
      totalCount: 0,
      debounceSearchPeron: null,
      loading: false
    };
  },
  watch: {
    searchoOrgkey(val)
    {
      this.$refs.orgTree.filter(val);
    },
    searchoPersonKey(val)
    {
      this.debounceSearchPeron();
    }
  },
  computed:
  {
    ...mapGetters(["userInfo"]),
    checkPerosnList()
    {
      let tampList = [];
      this.personUnidArr.map(pre_unid =>
      {
        let tampArr = pre_unid.split("_");
        tampList.push({
          unid: tampArr[0],
          personCommonname: tampArr[1]
        });
      })
      return tampList;
    }
  },
  created()
  {
    this.debounceSearchPeron = debounce(this.onSearchPerson, 500, false)
  },
  methods: {
    //监听人员搜索
    onSearchPerson()
    {
      this.parame.pageNo = 1;
      this.parame.personCommonname = this.searchoPersonKey;
      this.getPersonList();
    },
    //监听滚动
    scrollMenu(e)
    {
      let poor = e.target.scrollHeight - e.target.clientHeight
      if (poor == parseInt(e.target.scrollTop) || poor == Math.ceil(e.target.scrollTop) || poor == Math.floor(e.target.scrollTop))
      {
        console.log("滚动到底");
        if (this.totalCount > this.personData.length)
        {
          this.loadMore();
        }
      }
    },
    //加载更多
    loadMore()
    {
      this.parame.pageNo++;
      this.loading = true;
      getPersonList(this.parame).then((res) =>
      {
        this.totalCount = res.result.totalCount || 0;
        this.personData.push(...(res.result.data || []));
      }).finally(() => { this.loading = false });
    },
    //过滤机构
    filterOrgNode(value, data)
    {
      if (!value) return true;
      return PinYinMatch.match(data["orgCommonname"], value);
    },
    //人员过滤
    filterMethod(query, item)
    {
      if (!query)
      {
        return true;
      }
      return PinYinMatch.match(item.personCommonname, query);
    },
    //显示弹窗
    show(showData, replaceFields, multiple, config)
    {
      //首先整理回显人员数据
      if (showData && showData.constructor == Array)
      {
        this.personDataArr = [...showData];
        this.personDataArr.forEach(item =>
        {

          this.personUnidArr.push(item.unid + "_" + item.personCommonname);
        })
      }
      console.log("选人配置")
      console.log(config)
      console.log("选人配置")

      this.allCompany = config.allCompany || false;
      this.getOrgTree();
      this.multiple = multiple || false;
      this.replaceFields = replaceFields || this.replaceFields;
      this.$nextTick(() =>
      {
        this.$refs.scrollMenuRef.wrap.addEventListener("scroll", this.scrollMenu);
      })
      // 创建promise
      return new Promise((resolve, reject) =>
      {
        this.promiseStatus = {
          resolve,
          reject,
        };
      });
    },
    //删除人员
    handleDelPerson(P_PersonItem)
    {
      let tampIndex = this.personUnidArr.findIndex(pre_item =>
      {
        return pre_item == P_PersonItem.unid + "_" + P_PersonItem.personCommonname;
      })
      this.personUnidArr.splice(tampIndex, 1);
    },
    //全选或取消全选
    handleCheckAllChange(val)
    {

      console.log("全选");
      if (JSON.parse(val))
      {
        //全选
        this.personData.map((item) =>
        {
          console.log(item);
          if (this.personUnidArr.indexOf(item.unid + "_" + item.personCommonname) === -1)
          {
            this.personUnidArr.push(item.unid + "_" + item.personCommonname);
          }
        })
      }
      else
      {
        // 取消全选
        this.personData.map(item =>
        {
          let tampIndex = this.personUnidArr.indexOf(item.unid + "_" + item.personCommonname);
          if (tampIndex >= 0)
          {
            this.personUnidArr.splice(tampIndex, 1);
          }
        })
      }
    },
    //确认按钮
    handleOk()
    {
      let selects = this.checkPerosnList;
      // if (selects && selects.length > 0) {
      if (this.multiple)
      {
        // 多选
        this.promiseStatus.resolve({
          choiceData: selects,
          replaceFields: this.replaceFields
        });
      } else
      {
        //单选
        this.promiseStatus.resolve({
          choiceData: selects[0] || {},
          replaceFields: this.replaceFields
        });
      }
      // } else {
      //   this.promiseStatus.resolve({
      //     choiceData: selects,
      //     replaceFields: this.replaceFields
      //   });
      // }
      //清空勾选项
      this.selectedKeys = [];

      this.destroyElement();
    },
    //清空已选项
    handelEmpty()
    {
      this.personUnidArr = [];
    },
    //取消按钮
    handleCancel()
    {
      //清空勾选项
      this.promiseStatus.reject({
        msg: "取消",
      });
      this.selectedKeys = [];
      this.destroyElement();
    },
    //监听树选择
    handleNodeClick(selectedKeys, info)
    {
      this.parame.pageNo = 1;
      if (selectedKeys.unid == -1)
      {
        this.parame.orgUnid = null;
      }
      else
      {
        this.parame.orgUnid = selectedKeys.unid;
      }
      this.$refs.orgTree.setCurrentKey(this.parame.orgUnid);
      this.getPersonList();
    },
    //监听人员选择
    onChangePerson(isAdd, e)
    {
      if (!this.multiple && isAdd)
      {
        //单选
        this.personUnidArr = [this.personUnidArr[this.personUnidArr.length - 1]];
      }
      else
      {
        //多选
      }
    },
    //获取机构
    getOrgTree()
    {
      let apiPermise;
      if (this.allCompany)
      {
        apiPermise = treeselect()
      }
      else
      {
        apiPermise = getCompanyTree()
      }
      apiPermise.then((res) =>
      {

        this.treeData = [{
          orgCommonname: "<全部人员>",
          orgFullname: "<全部人员>",
          parentUnid: null,
          unid: "-1"
        }]
        this.treeData.push(...(res.result || []));

        if (this.treeData.length > 0)
        {
          let findIndex = 0;
          this.treeData.forEach((element) =>
          {
            this.expandedKey.push(element.unid);
          });

          for (let i = 0; i < this.treeData.length; i++)
          {
            findIndex++;
            let pre_temp = this.treeData[i];
            if (pre_temp.unid == this.userInfo.orgUnid)
            {
              break;
            }
            let flag = false;
            if (pre_temp.children && pre_temp.children.length > 0)
            {
              for (let j = 0; j < pre_temp.children.length; j++)
              {
                let pre_son_item = pre_temp.children[j];
                findIndex++;
                if (pre_son_item.unid == this.userInfo.orgUnid)
                {
                  flag = true;
                  break;
                }
              }
            }
            if (flag)
            {
              break;
            }
          }

          // this.parame.orgUnid = this.treeData[0].unid;
          //cs 20230/5/6 首次只展示当前部门人员
          this.parame.orgUnid = this.userInfo.orgUnid;
          this.$nextTick(() =>
          {
            if (this.$refs.orgTree)
            {
              this.$refs.orgTree.setCurrentKey(this.parame.orgUnid);
              if (findIndex > 9)
              {
                this.$refs.orgScroll.wrap.scrollTop = (findIndex - 9) * 26;
              }
            }
          })

          this.getPersonList();
        }
        // else {
        //   this.getPersonList();
        // }
      });
    },
    /**
     * 获取人员列表
     */
    getPersonList()
    {
      this.loading = true;
      let apiPermise;
      if (this.allCompany)
      {
        apiPermise = getPersonListAll(this.parame)
      }
      else
      {
        apiPermise = getPersonList(this.parame)
      }
      apiPermise.then((res) =>
      {
        this.checkAll = true;
        this.totalCount = res.result.totalCount || 0;
        this.personData = res.result.data || [];
        //判断是否全选
        for (let i = 0; i < this.personData.length; i++)
        {
          let findObj = this.checkPerosnList.find(per_item =>
          {
            return per_item.unid == this.personData[i].unid;
          })
          if (findObj == null || findObj == undefined)
          {
            this.checkAll = false;
            break;
          }
        }
        if (this.personData.length == 0)
        {
          this.checkAll = false;
        }

      }).finally(() =>
      {
        this.loading = false;
      })
    },
    /**
     * cs 2022-4-8
     * 销毁组件
     */
    destroyElement()
    {
      this.popenevTVisible = false;
    },
    /**
     * cs 2023-12-25
     * 监听勾选机构
     */
    onCheckOrg(data, checked, indeterminate)
    {
      console.log(data)
      console.log(checked)
      console.log(indeterminate);

      let apiPermise;
      if (this.allCompany)
      {
        apiPermise = getPersonListAll({
          pageNo: 1,
          pageSize: 10000,
          delFlag: 0,
          state: 0,
          orgUnid: data.unid,
        })
      }
      else
      {
        apiPermise = getPersonList({
          pageNo: 1,
          pageSize: 10000,
          delFlag: 0,
          state: 0,
          orgUnid: data.unid,
        })
      }
      if (checked)
      {
        apiPermise.then(res =>
        {
          let personData = res.result.data || [];
          personData.map((item) =>
          {
            if (this.personUnidArr.indexOf(item.unid + "_" + item.personCommonname) === -1)
            {
              this.personUnidArr.push(item.unid + "_" + item.personCommonname);
            }
          })
        })
      }
      else
      {
        apiPermise.then(res =>
        {
          let personData = res.result.data || [];
          personData.map((item) =>
          {
            let tampIndex = this.personUnidArr.indexOf(item.unid + "_" + item.personCommonname);
            if (tampIndex >= 0)
            {
              this.personUnidArr.splice(tampIndex, 1);
            }
          })
        })
      }
    }
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-input__inner {
  padding-left: 10px;
  position: relative;
}
.choice-person-box {
  display: flex;

  .org-list {
    width: 250px;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
  }

  .person-list {
    width: 250px;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    margin: 0 20px;

    .person-item {
      display: block;
      height: 26px;
      line-height: 26px;
      padding-left: 25px;
    }
  }

  .search-input {
    width: 80%;
    margin: 20px 10px 0;
    height: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    ::v-deep .el-input__inner {
      border-radius: 100px;
    }
  }
}

.scorll-Y {
  height: 350px;
  margin-top: 10px;

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

//单选情况下 隐藏全选功能
.no-all-check ::v-deep {
  .el-transfer-panel__header {
    .el-checkbox__input {
      display: none;
    }
  }
}

.btn-person-cacle {
  cursor: pointer;
  color: red;
  font-size: 14px;
}
</style>
